﻿using Douyu.Api.Entity;
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.Net;
using System.Threading.Tasks;

namespace Douyu.Api
{
    public static class EntityUtils
    {

        #region ToEntity

        /// <summary>
        /// 根据URL获取列表数据
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="url"></param>
        /// <returns></returns>
        public static async Task<IEntity<IEnumerable<T>>>  ToEntityListAsync<T>(this string url)
            where T :class
        {
            try
            {
                var client = new WebClient();
                var json = await client.DownloadStringTaskAsync(url);

                var obj = JsonConvert.DeserializeObject<Entity<IEnumerable<T>>>(json);
                return obj;
            }
            catch (Exception ex)
            {
                return new Entity<IEnumerable<T>> { Error = -1, Msg = ex.Message };
            }
        }

        /// <summary>
        /// 根据URL获取对象数据
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="url"></param>
        /// <returns></returns>
        public static async Task<IEntity<T>> ToEntityAsync<T>(this string url)
            where T : class
        {
            try
            {
                var client = new WebClient();
                var json = await client.DownloadStringTaskAsync(url);

                return JsonConvert.DeserializeObject<Entity<T>>(json);
            }
            catch (Exception ex)
            {
                return new Entity<T> { Error = -1, Msg = ex.Message };
            }
        }

        #endregion

        #region ToRoomKey

        public static string ToRoomKey(this int? cateId, string cateName)
        {
            if(cateId.HasValue)
            {
                return cateId.ToString();
            }
            else if(string.IsNullOrEmpty(cateName) || string.IsNullOrWhiteSpace(cateName))
            {
                return string.Empty;
            }
            else
            {
                return cateName;
            }
        }

        #endregion

        /// <summary>
        /// 格式化URL
        /// </summary>
        /// <param name="str"></param>
        /// <param name="args"></param>
        /// <returns></returns>
        public static string Fmt(this string str, params object[] args)
        {
            return string.Format(str, args);
        }

    }

}
